import { ref, watch } from 'vue'
import { defineStore } from 'pinia'

// 关注的作者接口
export interface FollowedAuthor {
  id: string | number
  name: string
  icon: string
  description?: string
}

const getStorageKey = (): string => {
  const currentPhone = localStorage.getItem('currentPhoneNumber')
  if (!currentPhone) {
    return 'follows_guest'
  }
  return `follows_${currentPhone}`
}

// 从本地存储加载数据
const loadFromStorage = (): FollowedAuthor[] => {
  try {
    const currentPhone = localStorage.getItem('currentPhoneNumber')
    if (!currentPhone) {
      return []
    }

    const users = JSON.parse(localStorage.getItem('users') || '[]')
    const user = users.find((u: any) => u.phoneNumber === currentPhone)

    if (user && user.follows && Array.isArray(user.follows)) {
      return user.follows
    }
    return []
  } catch (error) {
    console.error('加载关注列表失败:', error)
    return []
  }
}

// 保存到本地存储
const saveToStorage = (follows: FollowedAuthor[]) => {
  try {
    const currentPhone = localStorage.getItem('currentPhoneNumber')
    if (!currentPhone) {
      return
    }

    const users = JSON.parse(localStorage.getItem('users') || '[]')
    const userIndex = users.findIndex((u: any) => u.phoneNumber === currentPhone)

    if (userIndex !== -1) {
      users[userIndex].follows = follows
      localStorage.setItem('users', JSON.stringify(users))
    } else {
      // 如果用户不存在，创建新用户对象
      const newUser = {
        phoneNumber: currentPhone,
        follows: follows
      }
      users.push(newUser)
      localStorage.setItem('users', JSON.stringify(users))
    }
  } catch (error) {
    console.error('保存关注列表失败:', error)
  }
}

export const useFollowsStore = defineStore('follows', () => {
  // 关注的作者列表
  const followedAuthors = ref<FollowedAuthor[]>([])

  // 从本地存储加载数据
  const loadFollows = () => {
    followedAuthors.value = loadFromStorage()
  }

  // 保存到本地存储
  const saveFollows = () => {
    saveToStorage(followedAuthors.value)
  }

  // 添加关注
  const addFollow = (author: { id: string | number; name: string; icon?: string; description?: string }) => {
    if (!author || !author.id) return false

    // 检查是否已关注
    const existingIndex = followedAuthors.value.findIndex(item => String(item.id) === String(author.id))
    if (existingIndex !== -1) {
      // 已关注，返回 false
      return false
    }

    // 构建关注项
    const followItem: FollowedAuthor = {
      id: author.id,
      name: author.name || '未知',
      icon: author.icon || '',
      description: author.description || ''
    }

    // 添加到数组
    followedAuthors.value.push(followItem)

    // 自动保存到本地存储
    saveFollows()
    return true
  }

  // 取消关注
  const removeFollow = (authorId: string | number) => {
    const index = followedAuthors.value.findIndex(item => String(item.id) === String(authorId))
    if (index !== -1) {
      followedAuthors.value.splice(index, 1)
      saveFollows()
      return true
    }
    return false
  }

  // 检查是否已关注
  const isFollowed = (authorId: string | number): boolean => {
    return followedAuthors.value.some(item => String(item.id) === String(authorId))
  }

  // 切换关注状态
  const toggleFollow = (author: { id: string | number; name: string; icon?: string; description?: string }) => {
    if (!author || !author.id) return false

    if (isFollowed(author.id)) {
      return removeFollow(author.id)
    } else {
      return addFollow(author)
    }
  }

  // 清空关注列表
  const clearFollows = () => {
    followedAuthors.value = []
    saveFollows()
  }

  // 监听登录状态变化，重新加载数据
  const handleLoginChange = () => {
    loadFollows()
  }

  // 初始化：从本地存储加载
  loadFollows()

  // 监听 localStorage 中 currentPhoneNumber 的变化
  if (typeof window !== 'undefined') {
    window.addEventListener('storage', (e) => {
      if (e.key === 'currentPhoneNumber') {
        loadFollows()
      }
    })
  }

  return {
    followedAuthors,
    addFollow,
    removeFollow,
    isFollowed,
    toggleFollow,
    clearFollows,
    loadFollows,
    handleLoginChange
  }
})

